import React, { Component } from 'react'
import { connect } from 'react-redux'
import cloneDeep from 'lodash/cloneDeep'
import { originData } from '@utils/Global'
import PlayController from '@utils/PlayController'
import ReplayDmItem from './replayDmItem'
import { ReplayAction } from '@act'
const { setReplayDmList } = ReplayAction

class ReplayDm extends Component {
  handleShowDm = (obj) => {
    const { list: _list, dispatch } = this.props
    var dmList = cloneDeep(_list)
    const msgId = obj.task ? parseInt(obj.task.id) : -1
    dmList = dmList.map((_, index) => {
      if (parseInt(index) <= msgId) {
        _.show = true
      } else {
        _.show = false
      }
      return _
    })
    dispatch(setReplayDmList(dmList))
    obj.callback && obj.callback()
  }
  renderContent() {
    const { list } = this.props
    var items = []
    list.map((item, index) => {
      if (item.show) {
        items.push(
          <ReplayDmItem item={item} key={index} index={index} />
        )
      }
    })
    return items
  }
  scrollToBottom() {
    console.log('scrollToBottom')
    const clientHeight = this.dmListDiv.clientHeight; //可视区域高度
    const scrollTop = this.dmListDiv.scrollTop;  //滚动条滚动高度
    const scrollHeight = this.dmListDiv.scrollHeight; //滚动内容高度
    this.dmListDiv.scrollTop = scrollHeight - clientHeight
  }
  componentDidMount() {
    PlayController.setDmCallback(this.handleShowDm)
  }
  componentDidUpdate(prevProps) {
    const { list } = this.props
    const { list: preList } = prevProps
    const showList = list.filter((_) => { return _.show })
    const preShowList = preList.filter((_) => { return _.show })
    if (showList.length !== preShowList.length) {
      this.scrollToBottom()
    }
  }
  render() {
    const { showDm } = this.props
    const className = showDm ? 'replay_dm_con ' : 'replay_dm_con hide'
    return (
      <div className={className}>
        <div className="dm_list_outer">
          <div className="dm_list" ref={r => this.dmListDiv = r}>
            {this.renderContent()}
          </div>
        </div>
      </div>
    )
  }
}
const mapStateTopProps = (state) => {
  return {
    list: state.ReplayState.dmList,
    showFooter: state.ReplayState.showType.footer,
    showDm: state.ReplayState.showType.dm
  }
}
export default connect(mapStateTopProps)(ReplayDm)
